﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using NPOI;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS;
using NPOI.Util;
using NPOI.SS.UserModel;
using System.Text.RegularExpressions;
using NPOI.SS.Util;

namespace TaxBusiness.BLL
{
    public class DataRenderToExcel
    {
        public static Stream RenderDataTableToExcel(DataTable SourceTable)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            ISheet sheet = workbook.CreateSheet("导出结果");
            IRow headerRow = sheet.CreateRow(0);

            // handling header. 
            ICellStyle HeadercellStyle = workbook.CreateCellStyle();
            HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            //字体
            NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
            headerfont.Boldweight = (short)FontBoldWeight.Bold;
            HeadercellStyle.SetFont(headerfont);

            foreach (DataColumn column in SourceTable.Columns)
            {
                ICell cell = headerRow.CreateCell(column.Ordinal);
                cell.SetCellValue(column.ColumnName);
                cell.CellStyle = HeadercellStyle;
            }


            ICellStyle cellStyle = workbook.CreateCellStyle();

            //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
            //cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


            NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
            cellfont.Boldweight = (short)FontBoldWeight.Normal;
            cellStyle.SetFont(cellfont);


            // handling value. 
            int rowIndex = 1;
            int cellIndex = 0;
            foreach (DataRow row in SourceTable.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);

                foreach (DataColumn column in SourceTable.Columns)
                {
                    //dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    ICell cell = dataRow.CreateCell(cellIndex);
                    cell.SetCellValue(row[column].ToString());
                    cell.CellStyle = cellStyle;
                    cellIndex++;
                    
                }
                cellIndex = 0;
                rowIndex++;
            }

            for (int i = 0; i < cellIndex; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            sheet = null;
            headerRow = null;
            workbook = null;

            return ms;
        }

        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');

                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');

                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    try
                    {
                        string a = strRows[r].Split('#')[1].Trim();
                        if (a.Equals("null"))
                        {
                            dr[r] = "";
                        }
                        else
                        {
                            dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                        }
                    }
                    catch (Exception e)
                    {

                        throw e;
                    }
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            try
            {
                if (tb != null)
                {
                    return tb;
                }
                else
                {
                    throw new Exception("解析错误");
                }
            }
            catch (Exception e)
            {

                throw e;
            }
        }

        public static Stream RenderCountToExcel(DataTable SourceTable)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            ISheet sheet = workbook.CreateSheet("导出结果");
            IRow headerRow = sheet.CreateRow(0);

            // handling header. 
            string[] cellNames = new string[]{"股权转让", "注销", "两税核实", "资格认定", "减免税", "税前扣除", "弥补亏损", "房产评估", "小型微利", "土地增值税", "企业内审", "临时汇缴", "其他单项", "综合代理", "代理记账", "代开发票", "汇算清缴", "工程审计", "房地产咨询", "协作培训", "注会业务", "其他业务"};
            string[] subCellNames = new string[] { "UnitName", "tp11", "ctp11", "tp12", "ctp12", "tp13", "ctp13", "tp14", "ctp14", "tp15", "ctp15", "tp16", "ctp16", "tp17", "ctp17", "tp18", "ctp18", "tp19", "ctp19", "tp20", "ctp20", "tp21", "ctp21", "tp22", "ctp22", "tp23", "ctp23", "tp2", "ctp2", "tp3", "ctp3", "tp4", "ctp4", "tp5", "ctp5", "tp6", "ctp6", "tp7", "ctp7", "tp8", "ctp8", "tp9", "ctp9", "tp10", "ctp10" };

            ICellStyle HeadercellStyle = workbook.CreateCellStyle();
            HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            //字体
            NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
            headerfont.Boldweight = (short)FontBoldWeight.Bold;
            HeadercellStyle.SetFont(headerfont);

            ICell firstCell = headerRow.CreateCell(0);
            firstCell.SetCellValue("单位名称");
            sheet.AddMergedRegion(new CellRangeAddress(0, 1, 0, 0));
            firstCell.CellStyle = HeadercellStyle;
            
            int c = 1;
            foreach (string cellName in cellNames)
            {
                ICell cell = headerRow.CreateCell(c);
                cell.SetCellValue(cellName);
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, c, c + 1));
                cell.CellStyle = HeadercellStyle;
                c += 2;
            }
            IRow subHeaderRow = sheet.CreateRow(1);
            for (int n = 1; n < cellNames.Length * 2; n = n + 2)
            {
                ICell cell = subHeaderRow.CreateCell(n);
                cell.SetCellValue("元");
                ICell cell2 = subHeaderRow.CreateCell(n + 1);
                cell2.SetCellValue("笔");
                cell.CellStyle = HeadercellStyle;
                cell2.CellStyle = HeadercellStyle;
            }

            ICellStyle cellStyle = workbook.CreateCellStyle();

            //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
            //cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


            NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
            cellfont.Boldweight = (short)FontBoldWeight.Normal;
            cellStyle.SetFont(cellfont);


            // handling value. 
            int rowIndex = 2;
            int cellIndex = 0;
            foreach (DataRow row in SourceTable.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);

                foreach (string column in subCellNames)
                {
                    //dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    ICell cell = dataRow.CreateCell(cellIndex);
                    cell.SetCellValue(row[column].ToString());
                    cell.CellStyle = cellStyle;
                    cellIndex++;

                }
                cellIndex = 0;
                rowIndex++;
            }

            for (int i = 0; i < cellIndex; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            sheet = null;
            headerRow = null;
            workbook = null;

            return ms;
        }

    }
}
